<?php
/**
 * 订单操作Action
 * @author hushuai
 *
 */
class OrderAction extends CommonAction{
	
	private $order = "Order";
	
	/**
	 * 确认订单
	 * 检查数据
	 * 获取商品列表
	 */
	public function confirm(){
		
		$order    = D($this->order);
		$outletid = $this->_param("id","intval",0);
		
		//session中保存的用户地址信息
		$query = addressJsonDecode();
		$this->assign("query",$query);
		
		//如果没有选择城市或者没有选择具体地址，那么就要返回去重新选择
		if(empty($query['city'])||empty($query['adds'])){
			$this->assign("noneCity","1");
		}
		
		//获取地址详情
		if($query['id']){
			$one['id'] = $query['id'];
			$meth = sendRest('RMS/Address/detail',$one);
			$this->assign('memaddress',$meth['data']);
		}
		
		//获取餐厅信息
		$cat['id'] = $outletid;
		$outlet    = sendRest("BDC/Outlet/detail",$cat);
		$outlet    = $order->getYuding($outlet['data']);	//判断是否为预定餐
		$this->assign("outlet",$outlet);
		
		//获取城市联系电话
		$telphone = $order->getCityTel($query);
		$this->assign("telphone",$telphone);
		
		//系统配置
		$list = F("Sysconfig");                         //系统配置
		$this->assign("taste",   C("TASTE"));           //获取口味信息
		$this->assign("sdrink",  C("IS_SEND_DRINK"));   //读取赠送的饮料信息
		$this->assign("isdrink",$list['cfg']['drink']); //读取饮料赠送权限
		
		//获取用户购物车列表
		$user = getMember();
		$map['dataid']   = $user['id'];
		$map['outletid'] = $outletid;
		$cart = sendRest("RMS/Cart/view",$map);
		$arr  = $order->getDishesTime($cart['data']);   //查询菜品是否需要延时
		$this->assign("cart",$arr);
		
		//计算用户购物车中商品总价格
		$map['dataid']   = $user['id'];
		$map['outletid'] = $outletid;
		$totalprice = sendRest("RMS/Cart/calculateTotal", $map);
		
		//服务费
		$dlivery = session("dliveryfee");
		$this->assign("dliveryfee",$dlivery);
		
		//总价
		$total = $totalprice['data']+$dlivery;
		$this->assign("totalprice",$total);
		
		//session中服务时间
		$dliverytime = session("dliverytime");
		$this->assign("dliverytime",$dliverytime);
		
		//会员信息
		if(cookie(C('USER_AUTH_KEY'))){
			$member = M('Member')->find(cookie(C('USER_AUTH_KEY')));
			$this->assign('member',$member);
		}
		
		if(IS_POST){
			
			//预订单时间
			if($_POST['time']==-1){
				if(empty($_POST['sdltime']) || empty($_POST['edltime'])){
					$this->error(L('ord_ele_tip_checked'));exit;
				}
			}
			
			//获取用户信息
			$user = getMember();
			
			//处理地址
			$model = D("Address")->order_address($user,$_POST);
			
			//处理时间
			$time       = $_POST['time'];        //所需时间
			$dishestime = $_POST['dishestime'];  //菜品所需时间
			if($time==-1){//预订单时间
				$model['ydtime']   = $_POST['ydtime'];
				$model['sdltime']  = strtotime($_POST['ydtime'].' '.$_POST['sdltime']);
				$model['edltime']  = strtotime($_POST['ydtime'].' '.$_POST['edltime']);
				$model['isyuding'] = 1;//是否预定餐，1是2否
			}else{
				$timeduan = $this->getedltime($time,$dishestime);
				$model['sdltime']  = $timeduan['now'];
				$model['edltime']  = $timeduan['after'];
				$model['isyuding'] = $_POST['yuding'];//是否预定餐，1是2否
			}

			if($_POST['foodfee']<50){
				$model['isdrink'] = 0;
			}else{
				$model['isdrink'] = $_POST['isdrink'];
			}
			
			//将数组转成json字符串
			//$model['isdrink']       = $_POST['isdrink'];
			$model['isinvoice']     = $_POST['isinvoice'];
			$model['isprint']       = $_POST['isprint'];
			$model['isconfirm']     = $_POST['isconfirm'];
			$model['content']       = $_POST['content'];
			$model['city']          = $_POST['city'];
			$model['outletid']      = $this->_param("outid","intval",0);
			$model['orderno']       = createOrderNo();
			$model['ordertime']     = time();
			$model['invoice_title'] = $_POST['invoice_title']; //发票抬头
			//$model['shipfee']       = $_POST['shipfee'];
			$model['shipfee']       = session("dliveryfee");
			$model['ip']            = get_client_ip();
			$model['addressid']     = $query['siteid'];
			Log::write('Dingdan1:'.var_export($model,true),Log::ERR);

			$where['dataid']   = $model['dataid'];
			$where['outletid'] = $model['outletid'];
			$cart = sendRest("RMS/Cart/view",$where,'post');
			$data = $cart['data'];
			Log::write('UserInfo:'.var_export($map,true),Log::ERR);
			Log::write('UserCart:'.var_export($cart,true),Log::ERR);
			
			//如果购物车为空
			if(empty($data['list']) || $data['count']==0 || $data['count']==null){
				$where['dataid']   = cookie('memberGuestId');
				$where['outletid'] = $model['outletid'];
				$cart = sendRest("RMS/Cart/view",$where,'post');
				$data = $cart['data'];
				Log::write('UserInfo2:'.var_export($where,true),Log::ERR);
				Log::write('UserCart2:'.var_export($data,true),Log::ERR);
				if($data['list']){
					$model['dataid']   = cookie('memberGuestId');
					$model['tableid']  = 'Guest';
				}else{
					$this->error('订单异常，请稍后重试！');exit;
				}
			}

			//如果配送费为空，则重新计算一次配送费
			if(empty($model['shipfee']) || $model['shipfee']==0 || $model['shipfee']==null){
				$one['foodfee']   = $_POST['foodfee'];
				$one['user']      = addressJsonDecode();
				$one['outletid']  = $this->_param("outid","intval",0);
				$model['shipfee'] = D('Order')->cullShipfee($one);
			}
			
			$outlet = $order->getOutletDetail($model);                     //获取餐厅信息
			$total  = $order->get_tprice_total($data,$outlet);             //计算用户购物车中商品总价格
			$status = $order->get_outlet_timestamp($outlet,$model,$total); //判断是否是减免配送费时间内    
			
			//根据优惠时间段计算订单金额
			$model = $order->get_order_total($status,$total,$model);
			Log::write('Dingdan2:'.var_export($model,true),Log::ERR);
			
			$json = sendRest("OMS/Order/add",$model,"post");
			$orderid = $json['data'];
			redirect(U('Order/complete','orderid='.$orderid));
		}
		$this->display();	
	}
	
	/**
	 * 下单成功
	 */
	public function complete(){
		
		//根据订单id查询订单信息
		$orderid['id'] = $this->_get("orderid","intval",0);
		$orderDetail   = sendRest("OMS/Order/find",$orderid);
		$this->assign("orderdetail",$orderDetail['data']);
		
		//根据门店编号查询门店信息
		$outlet['id'] = $orderDetail['data']['outletid'];
		$outdetail    = sendRest("BDC/Outlet/detail",$outlet);
		$this->assign("outdetail",$outdetail['data']);
		
		//根据订单编号查询订单信息
		$map['orderno'] = $orderDetail['data']['orderno'];
		$odetail        = sendRest("OMS/Order/byorderno",$map);
		$this->assign("odetail",$odetail['data']);
		
		$this->assign("sdrink",  C("IS_SEND_DRINK"));   //读取赠送的饮料信息
		$this->display();
	}
	
	public function editask(){
		
		$map['ask'] = $this->_param("ask",   "trim",    "");
		$map['id']  = $this->_param("cartid","intval",  0);
		sendRest("RMS/Cart/editask",$map);
	} 
	
	//根据当前时间获取后面的时间
	private function getedltime($times,$dishestime){
		
		$ss    = intval($times+$dishestime)*60;
		$now   = time();
		$after = $ss+$now;
		
		return  array("now"=>$now,"after"=>$after);
	}
	
	public function printpage(){
		
		//订单信息
		$id = $this->_param("id","intval",0);
		$json = sendRest("OMS/Order/detail",array("id"=>$id));
		$this->assign("detail",$json['data']);
		
		//订单备注信息
		//$addid    = $json['data']['id'];
		//$orderbak = sendRest("OMS/Order/orderbakList",array('id'=>$addid));
		//$this->assign("orderbak",$orderbak['data']);
		
		//餐厅信息
		$outletid = $json['data']['outletid'];
		$outlet   = sendRest("BDC/Outlet/detail",array("id"=>$outletid));
		$this->assign("outlet",$outlet['data']);
		
		//订单详情信息
		$map['orderno'] = $json['data']['orderno'];
		$data = sendRest("OMS/Order/dlist",$map);
		
		$totalPrice = 0;
		foreach($data['data'] as $k=>$v){
			$totalPrice += $v['price']*$v['amount'];
			$data['data'][$k]['attr'] = json_decode($v['attr'],true);
			if($v['flag']=="dishes"){
				$cat['id'] = $v['pid'];
				$view = sendRest("RMS/Product/dishesDetail",$cat);
				$data['data'][$k]['detail']         = $view['data'];
				$data['data'][$k]['detail']['gnfr'] = json_decode($view['data']['gnfr'],true);
			}
		}
		
		$this->assign("totalPrice",$totalPrice);
		$this->assign("dlist",$data['data']);
		$this->assign("id",$id);
		
		$this->display();
	}
	
	public function pdf(){
	
		//订单信息
		$id = $this->_param("id","intval",0);
		$json = sendRest("OMS/Order/detail",array("id"=>$id));
		$this->assign("detail",$json['data']);
	
		//订单备注信息
		//$addid    = $json['data']['id'];
		//$orderbak = sendRest("OMS/Order/orderbakList",array('id'=>$addid));
		//$this->assign("orderbak",$orderbak['data']);
	
		//餐厅信息
		$outletid = $json['data']['outletid'];
		$outlet   = sendRest("BDC/Outlet/detail",array("id"=>$outletid));
		$this->assign("outlet",$outlet['data']);
	
		//订单详情信息
		$map['orderno'] = $json['data']['orderno'];
		$data = sendRest("OMS/Order/dlist",$map);
	
		$totalPrice = 0;
		foreach($data['data'] as $k=>$v){
			$totalPrice += $v['price']*$v['amount'];
			$data['data'][$k]['attr'] = json_decode($v['attr'],true);
			if($v['flag']=="dishes"){
				$cat['id'] = $v['pid'];
				$view = sendRest("RMS/Product/dishesDetail",$cat);
				$data['data'][$k]['detail']         = $view['data'];
				$data['data'][$k]['detail']['gnfr'] = json_decode($view['data']['gnfr'],true);
			}
		}
	
		$this->assign("totalPrice",$totalPrice);
		$this->assign("dlist",$data['data']);
		$this->assign("id",$id);
	
		$this->display();
	}
	
	/**
	 * 导出pdf
	 */
	public function daochu(){
		vendor('Tcpdf.tcpdf');
		$pdf=new Tcpdf();
		
		$id  = $this->_param('id');
		$html = D('Order')->getHtml($id);
		//$html = $this->fetch('pdf1');
		
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Nicola Asuni');
		$pdf->SetTitle('TCPDF Example 038');
		$pdf->SetSubject('TCPDF Tutorial');
		$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING);
		$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
			require_once(dirname(__FILE__).'/lang/eng.php');
			$pdf->setLanguageArray($l);
		}
		$pdf->SetFont('helvetica', '', 20);
		$pdf->AddPage();
		$txt = '';
		$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
		$pdf->SetFont('stsongstdlight', '', 10);
		$txt = 'こんにちは世界';
		//$pdf->WriteHtml(0, $htm, '', 0, 'L', true, 0, false, false, 0);
		$pdf->writeHTML($html, true, false, true, false, '');
		$pdf->Output('example_038.pdf', 'I');
	}

	/**
	 * 订单处理,转到支付
	 * 处理地址
	 * 添加订单详情
	 * 转到支付页面
	 */
	public function payment(){
		
		$order = D("Order"); 
		$rows  = $order->checkOrder();
		
		if(IS_POST && $rows['flag']){
			
			//处理地址
			$address = D("Address");
			$res     = $address->orderAddress();
			if(empty($res['id'])){
				$this->error($res['info']);
			}	
			
			$order->create();
			$orderno = $order->dealOrder($order,$res['id'],$rows['table']);
			
			if($orderno){
				session("orderno",$orderno);
			}else{
				$this->error(L('ord_ele_tip_proidnone'),U("Cart/mycart"));
			}
			
		}else{
			$orderno = $this->_param("orderno","trim",session("orderno"));
		}
		
		$flag = false ;
		if($orderno){
			$user   = getMember();
			$map['userid']  = $user['id'];
			$map['orderno'] = $orderno;
			$row = $order->where($map)->find();
			if($row['id']){
				$flag = true ;
			}
		}
				
		if($flag){
			$url   = $order->callPayFunc($row,"getCode");
			redirect($url);//ord_ele_tip_jumppay echo $url; exit();
		}else{
			$this->error(L('ord_ele_tip_noneorder'));
		}
		
	}
	
	/**
	 * express
	 * paypal快捷支付
	 * 检查数据
	 */
	public function express(){

		$order = D("Order");
		$rows  = $order->checkOrder();
		if($rows['flag']){
			$order->create();
			$order->payment = "Paypal";
			$orderno = $order->dealOrder($order,0,$rows['table']);
			if(empty($orderno)){
				$this->error(L('ord_ele_tip_proidnone'),U("Cart/mycart"));
			}else{
				session("orderno",$orderno);
			}
		}else{
			$orderno = $this->_param("orderno","trim",session("orderno"));
		}
		
		$flag = false ;
		if($orderno){
			$user   = getMember();
			$map['userid']  = $user['id'];
			$map['orderno'] = $orderno;
			$row = $order->where($map)->find();
			if($row['id']){
				$flag = true ;
			}
		}
		
		if($flag){
			$url  = $order->callPayFunc($row,"getCode");
			redirect($url);
		}else{
			$this->error(L('ord_ele_tip_noneorder'),U("Cart/mycart"));
		}
	}
	
	/**
	 * payal快捷支付
	 * 订单确认页面
	 * 订单确认支付处理
	 */
	public function paypal(){
	
		$order = D("Order");
		$user  = getMember();
		$map['userid'] = $user['id'];
		$map['id']     = $this->_param("orderno","trim","");
		$map['detail'] = 1;
		
		$json = sendRest("Order/userDetail",$map);
		$row  = $json['data'];
		
		if(IS_GET){
				
			$list = $order->confirmPaypal($map['id']);
			$this->assign("detail",$list);
			
			$paypal= $order->callPayFunc($row,"getExpressCheckoutDetails");
			$this->assign("paypal",$paypal);
			
			$this->assign("order",$row);
			$this->display();
		}else{
				
			$address = D("Address");
			$res     = $address->orderAddress();
			if(!$res['id']){
				$this->error($res['info']);
			}
			
			$order->create();
			$orderno = $order->dealPaypal($order,$res['id']);
			$paypal  = $order->callPayFunc($row,"confirmPayment");
			
			$pay = $order->getPayConfg($row['payment'],"lang");
			$this->assign("payment",$pay);
				
			$this->display("paysuccess");
		}
	}
	
	/**
	 * 支付返回
	 */
	public function paysuccess(){
		
		session("orderno",null);
		
		$order   = D("Order");
		$user    = getMember();
		
		$map['userid'] = $user['id'];
		$map['id']     = $this->_param("orderno","trim","");
		$map['detail'] = 0;
		
		$json = sendRest("Order/userDetail",$map);
		$row  = $json['data'];
		
		$pay = $order->getPayConfg($row['payment'],"lang");
		$this->assign("payment",$pay);
		
		if($json['status'] == 1){
			call_user_func("sence_check",'order_ok','ACTIVE',1,$this);
			call_user_func("sence_check",'order_ok','YHJ',1,$this);
		}
		$this->display();
	}
	
	/**
	 * 支付处理
	 * 异步操作
	 */
	public function paynotify(){
		
		$order   = D("Order");
		$orderno = $this->_get("orderno");
		$m['orderno'] = $orderno;
		
		$row  = $order->where($m)->find();
		//F("order_0",$row);

		$flag = $order->callPayFunc($row,"notify");
	}
	
	/**
	 * 取消支付订单
	 */
	public function paycancel(){
			
		$user    = getMember();
		$map['userid'] = $user['id'];
		$map['id']     = $this->_param("orderno","trim",0);
		$map['status'] = -1;
		$json = sendRest("Order/userStatus",$map);
			
		$this->assign("jumpUrl",U('Member/order_index'));
		$this->success($json['info']);
	}
	
	/**
	 * 查找门店
	 */
	public function mapOutlet(){
		
		$type = $this->_param("type","","area");
		$flag = 1;
		$info = "";
		$area = $this->_param("area","intval",0);
		
		if($type == "area"){
			
			$list = mapByArray($area,"area");
			
		}elseif($type == "address"){
			
			$addr = $this->_param("address","urldecode");
			$poin = mapAddressToPoi($addr);
			if($poin){
				$poit = $poin['lng'].",".$poin['lat'];
				$list = mapNearby(array("location"=>$poit));
			}
			//没有找到周边门店,默认读取区门店
			if(empty($list)){
				$list = mapByArray($area,"area");
			}
		}
		
		if(empty($list)){
			$info = "该区域没有找到对应的门店";
			$flag = 0;
		}
		
		$this->ajaxReturn($list,$info,$flag);
	}
	
	/**
	 * 订单确认页-异步获取优惠券优惠金额
	 */
	public function ajaxGetCouponTotal(){
		
		$id    = $this->_param('id','intval',0);
		$total = $this->_param('total');
		
		if($id&&$total){
			
			$map['couponid'] = $id;
			$map['total']    = $total;
			$json = sendRest("Coupon/find",$map);
			
			$json['coupon'] = number_format(($total-$json['data']),2);
			$json['total']  = number_format($total-$json['coupon'],2);
			
			$this->ajaxReturn($json);
		}else{
			$json['total'] = number_format($total,2);
			$this->ajaxReturn($json);
		}
	}
	
	/**
	 * 订单确认页-异步获取会员卡优惠金额
	 */
	public function ajaxGetVipTotal(){
		
		$userid = session(C('USER_AUTH_KEY')); 
		$total  = $this->_param('total');
		$id     = $this->_param('id');
		
		if($total&&$id){
			$map['userid'] = $userid;
			$json = sendRest("Vip/view",$map);
				
			$json['total']  = number_format(($total*($json['data']['discount']/100)),2);
			$json['coupon'] = number_format($total-$json['total'],2);
			
			$this->ajaxReturn($json);
		}else{
			$json['total'] = number_format($total,2);
			$this->ajaxReturn($json);
		}
	}
	
	/**
	 * 根据地址区域找到对应的配送方式
	 */
	public function shipArea(){
		
		$map['area'] = $this->_param("area","intval",0);
		$json = sendRest("Shipping/shipArea", $map);
		
		$this->assign("list",$json['data']);
		$content = $this->fetch("shipping");
		$this->ajaxReturn($content);
	}
	
	/**
	 * 计算运费
	 * @param $area    地区编号
	 * @param $total   总金额
	 * @param $amount  商品总数量
	 * @param $weight  商品总重量
	 * @param $shipid  配送方式编号
	 * @param $type    配送计算方式类型(byWeight,byNumber)
	 *
	 */
	public function shipCalc(){
		
		$table  = session(C('CART_TABLE'));
		$module = get_array_key("ORDER_TABLE",$table);
		$list   = D("Order")->getConfirmList($module);
	
		$m['area']   = $this->_param("area","intval",0);
		$m['total']  = doubleval($list['total']);
		$m['amount'] = intval($list['amount']);
		$m['weight'] = intval($list['weight']);
		$m['shipid'] = $this->_param("shipid","intval",0);
		//$m['type']   = $this->_get("type","trim",'byNumber');
		if($m['area'] && $m['total'] && $m['shipid'] && $m['weight']){
			
			$json = sendRest("Shipping/calc", $m);
			
			if($json['status'] == 1){
				$this->success($json['data']);
			}else{
				$this->error("不在配送区域内");
			}
		}else{
			$this->error("请选择配送方式");
		}
	}
	
	/**
	 * 计算服务费
	 */
	public function getDliveryfee(){
		
		$model = D('Order');
		$url   = "http://api.map.baidu.com/direction/v1";
		
		//城市配置
		$cityid  = D('Member')->getUserCityid();
		$cityarr = C('CITYID');
		$title   = $cityarr[$cityid][1];
		
		$c_lng    = $this->_param('c_lng','trim','');
		$c_lat    = $this->_param('c_lat','trim','');
		$y_lng    = $this->_param('y_lng','trim','');
		$y_lat    = $this->_param('y_lat','trim','');
		
		//餐厅详情
		$outletid = $this->_param('outletid','intval',0);
		$outlet = M('Outlet')->find($outletid);
		
		$map['origin']             = $c_lat.",".$c_lng; //餐厅经纬度
		$map['destination']        = $y_lat.",".$c_lng; //用户经纬度
		$map['output']             = "json";
		$map['ak']                 = "6RQGXCYLSCZzLuPgZnnSMMrd";
		$map['region']             = $title;
		$map['origin_region']      = $title;
		$map['destination_region'] = $title;
		
		$json = curlGet($url,$map);
		if($json['message']=='ok'){
			$distance = $json['result']['routes'][0]['distance'];
			
			$dliveryfee = $model->getDliveryfee($distance);
			
			//判断是否处于减免配送费用时间
			$exempt = D('Restaurant')->getDelivery($outlet,$dliveryfee);
			
			session("dliveryfee",$exempt['sever']);
			$this->ajaxReturn(array('status'=>1,'dliveryfee'=>$exempt['sever']));
		}else{
			$this->ajaxReturn(array('info'=>L('ord_ele_tip_ads_error')));
		}
	}
}
?>